//
//  FeaturesView.swift
//  AppleAppDemo
//
//  Created by 刘忠华 on 2025/9/9.
//

import SwiftUI

struct FeaturesView: View {
    @State private var selectedFeature: Feature? = nil
    @EnvironmentObject var focusManager: TVFocusManager
    
    private let features = [
        Feature(
            title: "SwiftUI 跨平台",
            description: "使用 SwiftUI 构建统一的用户界面，在不同平台上提供一致的用户体验",
            icon: "swift",
            color: .orange,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        ),
        Feature(
            title: "自适应布局",
            description: "根据设备类型和屏幕尺寸自动调整布局，确保在各种设备上都有良好的显示效果",
            icon: "rectangle.3.group",
            color: .blue,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        ),
        Feature(
            title: "平台特定功能",
            description: "充分利用每个平台的独特功能，如触控、鼠标、遥控器等交互方式",
            icon: "hand.tap",
            color: .green,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        ),
        Feature(
            title: "统一代码库",
            description: "维护单一代码库，减少重复代码，提高开发效率和代码质量",
            icon: "folder",
            color: .purple,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        ),
        Feature(
            title: "性能优化",
            description: "针对不同平台进行性能优化，确保应用在各种设备上都能流畅运行",
            icon: "speedometer",
            color: .red,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        ),
        Feature(
            title: "测试覆盖",
            description: "为所有平台提供完整的测试覆盖，确保功能的一致性和稳定性",
            icon: "checkmark.circle",
            color: .indigo,
            platforms: [.iOS, .iPadOS, .macOS, .tvOS]
        )
    ]
    
    var body: some View {
        Group {
            if PlatformDetector.isTVOS {
                TVScrollViewWrapper(pageIndex: 1) {
                    contentView
                }
                .onAppear {
                    // 功能页面出现时，确保焦点管理器知道当前在内容区域
                    focusManager.requestContentFocus()
                }
            } else {
                ScrollView {
                    contentView
                }
            }
        }
    }
    
    private var contentView: some View {
        VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 24)) {
            // 标题区域
            VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 20)) {
                Text("功能特性")
                    .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 36)))
                    .fontWeight(.bold)
                
                Text("探索我们的多平台功能")
                    .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 24)))
                    .foregroundColor(.secondary)
                    .multilineTextAlignment(.center)
            }
            .padding(.top, PlatformConfig.spacing(for: PlatformDetector.current, base: 16))
            .padding(.bottom, PlatformConfig.spacing(for: PlatformDetector.current, base: 32))
            
            // 功能列表
            LazyVStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                ForEach(features, id: \.title) { feature in
                    FeatureRow(feature: feature) {
                        selectedFeature = feature
                    }
                }
            }
            
            // 技术规格
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                Text("技术规格")
                    .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 28)))
                    .fontWeight(.bold)
                
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                    SpecRow(title: "开发语言", value: "Swift 5.0")
                    SpecRow(title: "UI框架", value: "SwiftUI")
                    SpecRow(title: "最低版本", value: "iOS 17.0+, macOS 14.0+, tvOS 17.0+")
                    SpecRow(title: "架构模式", value: "MVVM")
                    SpecRow(title: "数据存储", value: "UserDefaults + Core Data")
                }
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 24))
            .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 16))
            .shadow(color: .black.opacity(0.15), radius: 6, x: 0, y: 3)
            
            // 性能指标
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 20)) {
                Text("性能指标")
                    .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 28)))
                    .fontWeight(.bold)
                
                LazyVGrid(columns: [
                    GridItem(.flexible()),
                    GridItem(.flexible())
                ], spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 20)) {
                    MetricCard(title: "启动时间", value: "< 1s", color: .green)
                    MetricCard(title: "内存使用", value: "< 50MB", color: .blue)
                    MetricCard(title: "响应时间", value: "< 100ms", color: .orange)
                    MetricCard(title: "电池效率", value: "优秀", color: .purple)
                }
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 24))
            .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 16))
            .shadow(color: .black.opacity(0.15), radius: 6, x: 0, y: 3)
            
            // 功能分类展示
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                Text("功能分类")
                    .font(.title2)
                    .fontWeight(.bold)
                
                LazyVGrid(columns: [
                    GridItem(.flexible()),
                    GridItem(.flexible())
                ], spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                    CategoryCard(title: "核心功能", icon: "star.fill", color: .yellow, count: 8)
                    CategoryCard(title: "界面组件", icon: "rectangle.3.group", color: .blue, count: 12)
                    CategoryCard(title: "平台适配", icon: "globe", color: .green, count: 6)
                    CategoryCard(title: "性能优化", icon: "speedometer", color: .purple, count: 4)
                }
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 16))
            .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 12))
            .shadow(color: .black.opacity(0.1), radius: 4, x: 0, y: 2)
            
            // 用户反馈
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                Text("用户反馈")
                    .font(.title2)
                    .fontWeight(.bold)
                
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
                    FeedbackItem(rating: 5, comment: "界面设计很棒，使用体验流畅")
                    FeedbackItem(rating: 5, comment: "多平台支持做得很好")
                    FeedbackItem(rating: 4, comment: "功能丰富，期待更多更新")
                }
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 16))
            .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 12))
            .shadow(color: .black.opacity(0.1), radius: 4, x: 0, y: 2)
            
            // 更新日志
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                Text("更新日志")
                    .font(.title2)
                    .fontWeight(.bold)
                
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
                    UpdateItem(version: "v1.2.0", date: "2025-01-15", changes: ["新增tvOS滚动支持", "优化界面布局", "修复已知问题"])
                    UpdateItem(version: "v1.1.0", date: "2025-01-01", changes: ["添加多平台适配", "改进用户体验"])
                    UpdateItem(version: "v1.0.0", date: "2024-12-20", changes: ["初始版本发布", "基础功能实现"])
                }
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 16))
            .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 12))
            .shadow(color: .black.opacity(0.1), radius: 4, x: 0, y: 2)
            
            Spacer(minLength: PlatformConfig.spacing(for: PlatformDetector.current, base: 20))
        }
        .padding(.horizontal, PlatformConfig.spacing(for: PlatformDetector.current, base: 8))
        .navigationTitle("功能")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.large)
        #endif
        #if !os(tvOS)
        .sheet(item: $selectedFeature) { feature in
            FeatureDetailView(feature: feature)
        }
        #else
        .background(
            // tvOS 使用全屏导航
            NavigationLink(
                destination: selectedFeature != nil ? FeatureDetailView(feature: selectedFeature!) : nil,
                isActive: Binding(
                    get: { selectedFeature != nil },
                    set: { if !$0 { selectedFeature = nil } }
                )
            ) {
                EmptyView()
            }
        )
        #endif
    }
}

/// 功能模型
struct Feature: Identifiable {
    let id = UUID()
    let title: String
    let description: String
    let icon: String
    let color: Color
    let platforms: [Platform]
}

/// 功能行视图
struct FeatureRow: View {
    let feature: Feature
    let onTap: () -> Void
    
    private var backgroundColor: Color {
        return PlatformConfig.backgroundColor(for: PlatformDetector.current)
    }
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
                // 图标
                Image(systemName: feature.icon)
                    .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 20)))
                    .foregroundColor(feature.color)
                    .frame(width: PlatformConfig.fontSize(for: PlatformDetector.current, base: 32))
                
                // 内容
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 2)) {
                    Text(feature.title)
                        .font(.subheadline)
                        .fontWeight(.semibold)
                        .foregroundColor(.primary)
                        .multilineTextAlignment(.leading)
                    
                    Text(feature.description)
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .multilineTextAlignment(.leading)
                        .lineLimit(2)
                    
                    // 平台标签
                    PlatformTags(platforms: feature.platforms)
                }
                
                Spacer()
                
                // 箭头
                Image(systemName: "chevron.right")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 8))
            .background(backgroundColor)
            .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 8))
            .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
        }
        .buttonStyle(PlainButtonStyle())
    }
}

/// 平台标签
struct PlatformTags: View {
    let platforms: [Platform]
    
    var body: some View {
        HStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 4)) {
            ForEach(platforms, id: \.self) { platform in
                Text(platform.rawValue)
                    .font(.caption2)
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                    .padding(.horizontal, PlatformConfig.spacing(for: PlatformDetector.current, base: 6))
                    .padding(.vertical, PlatformConfig.spacing(for: PlatformDetector.current, base: 2))
                    .background(platformColor(platform))
                    .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 4))
            }
        }
    }
    
    private func platformColor(_ platform: Platform) -> Color {
        switch platform {
        case .iOS: return .blue
        case .iPadOS: return .purple
        case .macOS: return .gray
        case .tvOS: return .red
        }
    }
}

/// 功能详情视图
struct FeatureDetailView: View {
    let feature: Feature
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 24)) {
                    // 头部
                    VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                        Image(systemName: feature.icon)
                            .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 60)))
                            .foregroundColor(feature.color)
                        
                        Text(feature.title)
                            .font(.largeTitle)
                            .fontWeight(.bold)
                            .multilineTextAlignment(.center)
                        
                        Text(feature.description)
                            .font(.body)
                            .foregroundColor(.secondary)
                            .multilineTextAlignment(.center)
                    }
                    
                    // 支持的平台
                    VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                        Text("支持的平台")
                            .font(.headline)
                            .fontWeight(.semibold)
                        
                        LazyVGrid(columns: gridColumns, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
                            ForEach(feature.platforms, id: \.self) { platform in
                                PlatformTag(platform: platform)
                            }
                        }
                    }
                    
                    // 详细信息
                    VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                        Text("详细信息")
                            .font(.headline)
                            .fontWeight(.semibold)
                        
                        Text(detailedDescription)
                            .font(.body)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                }
                .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 20))
            }
            .navigationTitle("功能详情")
            #if os(iOS)
            .navigationBarTitleDisplayMode(.inline)
            #endif
            #if !os(tvOS)
            .toolbar {
                #if os(macOS)
                ToolbarItem(placement: .cancellationAction) {
                    Button("完成") {
                        dismiss()
                    }
                }
                #else
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成") {
                        dismiss()
                    }
                }
                #endif
            }
            #endif
        }
    }
    
    private var gridColumns: [GridItem] {
        let columnCount = PlatformDetector.isTV ? 2 : (PlatformDetector.isMacOS ? 4 : 2)
        return Array(repeating: GridItem(.flexible()), count: columnCount)
    }
    
    private var detailedDescription: String {
        switch feature.title {
        case "SwiftUI 跨平台":
            return "SwiftUI 是苹果推出的现代化 UI 框架，支持声明式编程，可以轻松构建跨平台应用。通过共享代码和平台特定的适配，我们可以在不同设备上提供一致的用户体验。"
        case "自适应布局":
            return "自适应布局使用 SwiftUI 的响应式设计原则，根据设备类型、屏幕尺寸和方向自动调整界面元素。这确保了应用在各种设备上都能提供最佳的用户体验。"
        case "平台特定功能":
            return "每个平台都有其独特的交互方式和功能特性。我们充分利用这些特性，为每个平台提供最适合的用户体验，如触控手势、鼠标交互、遥控器导航等。"
        case "统一代码库":
            return "通过共享代码库，我们可以减少重复代码，提高开发效率。同时，统一的代码结构也使得维护和更新变得更加容易，确保所有平台的功能保持同步。"
        case "性能优化":
            return "针对不同平台的硬件特性和系统要求，我们进行了专门的性能优化。这包括内存管理、渲染优化、网络请求优化等方面，确保应用在各种设备上都能流畅运行。"
        case "测试覆盖":
            return "我们为所有平台提供了完整的测试覆盖，包括单元测试、集成测试和 UI 测试。这确保了功能的一致性和稳定性，减少了跨平台开发中可能出现的问题。"
        default:
            return "这是一个强大的功能，为我们的多平台应用提供了重要的支持。"
        }
    }
}

/// 平台标签
struct PlatformTag: View {
    let platform: Platform
    
    var body: some View {
        HStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 4)) {
            Image(systemName: platformIcon)
                .font(.caption)
            
            Text(platform.rawValue)
                .font(.caption)
                .fontWeight(.medium)
        }
        .foregroundColor(.white)
        .padding(.horizontal, PlatformConfig.spacing(for: PlatformDetector.current, base: 8))
        .padding(.vertical, PlatformConfig.spacing(for: PlatformDetector.current, base: 4))
        .background(platformColor)
        .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 6))
    }
    
    private var platformIcon: String {
        switch platform {
        case .iOS: return "iphone"
        case .iPadOS: return "ipad"
        case .macOS: return "desktopcomputer"
        case .tvOS: return "tv"
        }
    }
    
    private var platformColor: Color {
        switch platform {
        case .iOS: return .blue
        case .iPadOS: return .purple
        case .macOS: return .gray
        case .tvOS: return .red
        }
    }
}

/// 规格行
struct SpecRow: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title)
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Spacer()
            
            Text(value)
                .font(.subheadline)
                .fontWeight(.medium)
        }
    }
}

/// 指标卡片
struct MetricCard: View {
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 6)) {
            Text(value)
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(color)
            
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
                .multilineTextAlignment(.center)
        }
        .frame(maxWidth: .infinity)
        .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 12))
        .background(color.opacity(0.1))
        .cornerRadius(8)
    }
}

/// 分类卡片
struct CategoryCard: View {
    let title: String
    let icon: String
    let color: Color
    let count: Int
    
    var body: some View {
        VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
            Image(systemName: icon)
                .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 28)))
                .foregroundColor(color)
            
            Text(title)
                .font(.headline)
                .fontWeight(.bold)
            
            Text("\(count) 项功能")
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 12))
        .frame(maxWidth: .infinity)
        .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
        .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 8))
        .shadow(color: .black.opacity(0.1), radius: 2, x: 0, y: 1)
    }
}

/// 反馈项目
struct FeedbackItem: View {
    let rating: Int
    let comment: String
    
    var body: some View {
        HStack(alignment: .top, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
            // 评分星星
            HStack(spacing: 2) {
                ForEach(1...5, id: \.self) { star in
                    Image(systemName: star <= rating ? "star.fill" : "star")
                        .font(.caption)
                        .foregroundColor(.yellow)
                }
            }
            
            Text(comment)
                .font(.subheadline)
                .foregroundColor(.primary)
            
            Spacer()
        }
        .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 8))
        .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
        .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 6))
        .shadow(color: .black.opacity(0.05), radius: 1, x: 0, y: 1)
    }
}

/// 更新项目
struct UpdateItem: View {
    let version: String
    let date: String
    let changes: [String]
    
    var body: some View {
        VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 6)) {
            HStack {
                Text(version)
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.blue)
                
                Spacer()
                
                Text(date)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 2)) {
                ForEach(changes, id: \.self) { change in
                    HStack(alignment: .top, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 4)) {
                        Text("•")
                            .font(.caption)
                            .foregroundColor(.blue)
                        
                        Text(change)
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
            }
        }
        .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 12))
        .background(PlatformConfig.backgroundColor(for: PlatformDetector.current))
        .cornerRadius(PlatformConfig.cornerRadius(for: PlatformDetector.current, base: 8))
        .shadow(color: .black.opacity(0.05), radius: 1, x: 0, y: 1)
    }
}

#Preview {
    NavigationView {
        FeaturesView()
    }
}
